package plus.xj17520.org.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import plus.xj17520.base.constants.Constants;
import plus.xj17520.base.query.ShopQuery;
import plus.xj17520.base.result.JSONResult;
import plus.xj17520.base.utils.EmailUtil;
import plus.xj17520.base.utils.MyStringUtil;
import plus.xj17520.base.utils.PwdUtil;
import plus.xj17520.base.utils.RedisService;
import plus.xj17520.org.domain.Employee;
import plus.xj17520.org.domain.Shop;
import plus.xj17520.org.domain.ShopRegisterDTO;
import plus.xj17520.org.mapper.EmployeeMapper;
import plus.xj17520.org.mapper.ShopMapper;
import plus.xj17520.org.service.IShopService;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @projectName: pethomeProject
 * @package: plus.xj17520.org.service.impl
 * @className: ShopServiceImpl
 * @author: XiaoJue
 * @description: TODO
 * @date: 2022/5/29 16:34
 * @version: 1.0
 */
@Service
public class ShopServiceImpl implements IShopService {
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    RedisService redisService;
    @Autowired
    EmailUtil emailUtil;

    @Value("${spring.mail.username}")
    private String addresser;
//
//
//    @Override
//    public JSONResult addOrUpdate(Shop Shop) {
//        if (Shop.getId() != null) {
//            shopMapper.updateByPrimaryKey(Shop);
//        }
//        else
//            shopMapper.insert(Shop);
//        return JSONResult.success();
//    }

/*    @Override
    public JSONResult findState(int state) {
        switch (state){
            case 1: return JSONResult.success(shopMapper.selectByExample(1));
            case 2: return JSONResult.success(shopMapper.selectByExample(2));
            case 3: return JSONResult.success(shopMapper.selectByExample(3));
            case 4: return JSONResult.success(shopMapper.selectByExample(4));
            default:return null;
        }
    }*/


    //
//    @Override
//    public JSONResult delete(Long id) {
//        shopMapper.deleteByPrimaryKey(id);
//        return JSONResult.success();
//    }
//
    @Override
    public JSONResult shopPageList(ShopQuery ShopQuery) {
        Example example = new Example(Shop.class);

        if (MyStringUtil.isNotEmpty(String.valueOf(ShopQuery.getState())))
            //精确查询
            example.and().andEqualTo("state", ShopQuery.getState());

        //分页
        PageHelper.startPage(ShopQuery.getCurrent(), ShopQuery.getSize());
        List<Shop> Shops = shopMapper.selectByExample(example);
        //返回查询结果集
        return JSONResult.success(new PageInfo<>(Shops));
    }

    //
//    @Override
//    public JSONResult batchDelete(ShopQuery ShopQuery) {
//        Long[] ids = ShopQuery.getIds();
//        for (Long id : ids)
//            shopMapper.deleteByPrimaryKey(id);
//        return JSONResult.success();
//    }
//
    // 店铺注册，将数据存储到店铺表和员工表中
    @Override
    public JSONResult register(ShopRegisterDTO dto) {
        /*
         * 给密码设置盐值
         * 1.设置state为1：待审核，新增店铺到shop表中
         * 2.表示注册店铺的用户为超管
         * 3.用户的shopId 与 shop主键一致
         * 4.新增用户到员工表中
         * */
        // 密码加密
        String uuid = IdUtil.fastSimpleUUID();
        String password = dto.getEmployee().getPassword();
        String newPwd = PwdUtil.getPwd(password, uuid);
        dto.getEmployee().setPassword(newPwd);
        // 设置店铺 state ，新增到表中
        dto.getShop().setState(Constants.SHOP_WAITING);
        shopMapper.insertSelective(dto.getShop());
        // 设置注册店铺人的字段属性，新增到表中
        dto.getEmployee().setSalt(Constants.USER_ON);
        dto.getEmployee().setShopAdmin(true);
        dto.getEmployee().setShopId(Math.toIntExact(dto.getShop().getId()));
        employeeMapper.insertSelective(dto.getEmployee());

        return JSONResult.success();
    }

    // 审核通过，发送邮箱激活
    @Override
    public JSONResult auditYes(Long id) {
        // 查找所有关联此店铺id的员工
        Example example = new Example(Employee.class);
        example.and().andEqualTo("shopId", id);
        List<Employee> employees = employeeMapper.selectByExample(example);
        // 创建一个由Redis管理的UUID，给激活链接创建一个失效时间
        String uuid = IdUtil.fastSimpleUUID();
        redisService.setStringKeyAndValue(uuid, shopMapper.selectByPrimaryKey(id), 30);
        // 识别为管理员的员工对象
        for (Employee employee : employees) {
            Boolean shopAdmin = employee.getShopAdmin();
            if (shopAdmin) {
                String text = "（链接30分钟之内有效）你的店铺已经审核通过，请点击: <a href= 'http://127.0.0.1:80/shop/activate/" + uuid + "'>激活店铺</a>";
                emailUtil.send(addresser, "宠物之家店铺激活邮件", text, employee.getEmail());
                return JSONResult.success();
            }
        }
        return JSONResult.error("网络异常，请稍后再试！");
    }

    // 邮件激活店铺，激活链接有时间失效限制，由Redis管理
    @Override
    public JSONResult activate(String uuid) {
        // 校验UUID是否符合，防止用户篡改以及失效
        if (redisService.hasKey(uuid)) {
            Shop shop = redisService.getKeyObjectValue(uuid, Shop.class);
            shop.setState(Constants.SHOP_ON);
            shopMapper.updateByPrimaryKeySelective(shop);
            return JSONResult.success("您的店铺已经成功激活！");
        }
        return JSONResult.error("激活失败，链接已经失效，请重新获取激活链接！");
    }

    // 审核驳回,给商家发送审核失败原因的邮件
    @Override
    public JSONResult auditNo(Shop shop) {
        shop.setState(Constants.SHOP_OFF);
        shopMapper.updateByPrimaryKeySelective(shop);

        String reason = shop.getReason();
        String suggest = shop.getSuggest();
        if (suggest == null || suggest.equals("")) {
            suggest = "无";
        }
        // 查找所有关联此店铺id的员工
        Example example = new Example(Employee.class);
        example.and().andEqualTo("shopId", shop.getId());
        List<Employee> employees = employeeMapper.selectByExample(example);
        // 识别为管理员的员工对象
        for (Employee employee : employees) {
            Boolean shopAdmin = employee.getShopAdmin();
            if (shopAdmin) {

                String text = "你的店铺已经审核失败，原因：" + reason + "审核意见" + suggest;
                emailUtil.send(addresser, "宠物之家店铺激活邮件", text, employee.getEmail());
                return JSONResult.success();
            }
        }
        return JSONResult.error("网络异常，请稍后再试！");
    }
    
}
